<?php


function md5_hash($text)
{
    return md5($text);
}

function aes_decrypt($encrypted_data, $key)
{
    if (strlen($key) !== 16) {
        die("AES 密钥必须为 16 字节");
    }

    $encrypted_data = base64_decode($encrypted_data);
    return openssl_decrypt($encrypted_data, "AES-128-ECB", $key, OPENSSL_RAW_DATA);
}

function fetch_encrypted_data($url, $post_data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(["data" => json_encode($post_data)]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded", "user-agent:K6OWL9LABh"]);

    $response = curl_exec($ch);

    if ($response === false) {
        die('Curl 错误: ' . curl_error($ch));
    }

    curl_close($ch);

    return $response;
}

function generate_aes_key($f4319D, $rand)
{
    $md5_hash = md5_hash($f4319D . $rand);
    return substr($md5_hash, 7, 16); // 取第 8 到 23 个字符
}

function zlib_decompress($data)
{
    return zlib_decode($data); // `zlib` 解压
}

function transform_encrypted_string($data)
{
    $data = substr($data, 128); // 去掉前 128 个字符
    $data = str_replace(["f", "b", "t", "y"], ["#", "f", "%", "t"], $data);
    $data = str_replace(["#", "%"], ["b", "y"], $data);
    return $data;
}

function calculate_f4319D($app_name, $package_name, $sign)
{
    $f4342q = "23295";  // 固定值
    $first_hash = md5_hash($f4342q . $app_name . $package_name . $sign);
    return md5_hash($first_hash . $app_name . $package_name);
}


function formatJsonToCsv($json)
{
    $data = json_decode($json, true);

    if ($data === null) {
        return "JSON 解析失败: " . json_last_error_msg();
    }

    $output = [];
    foreach ($data as $category) {
        if (!isset($category['name'], $category['data']) || !is_array($category['data']) || $category['name'] == "我的收藏") {
            continue;
        }

        $output[] = "\n" . $category['name'] . ',#genre#';
        foreach ($category['data'] as $item) {
            if (!isset($item['name'], $item['source']) || !is_array($item['source'])) {
                continue;
            }
            foreach ($item['source'] as $source) {
                $output[] = $item['name'] . ',' . $source;
            }
        }

    }

    return implode("\n", $output);
}


function getFinalRedirectUrl($url)
{
    //$url = "http://110.40.45.55:6633/12345/xg.php?id=凤凰中文台";
//    echo $url;
//    exit();
    //echo "开始执行";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    // 重要：只获取头部，不下载内容
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    // 减少超时设置
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 减少总超时时间
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 减少连接超时时间
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // 不自动跟随重定向
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'mitv');

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // 检查是否是重定向状态码
    if ($httpCode >= 300 && $httpCode < 400) {
        // 从响应头中获取重定向 URL
        preg_match('/Location:(.*?)\n/', $response, $matches);
        if (isset($matches[1])) {
            $redirectUrl = trim($matches[1]);
            curl_close($ch);
            return $redirectUrl;
        }
    }

    $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);

    return $finalUrl;
}
//$id = $_GET['id'] ?? "http://110.40.45.55:6633/12345/xg.php?id=凤凰中文台";
//echo  getFinalRedirectUrl($id);
//exit();


if (isset($_GET['getlist'])) {

// 配置参数
    $url = "http://110.40.45.55:6633/xiaoding/data125.php";
    $post_data = [
        "region" => "湖南",
        "nettype" => "电信",
        "rand" => "a60c8810e941400dea8540dc86e78c7a",
        "mac" => "00:db:d7:25:8d:fa",
        "androidid" => "1166f9e3f11f3648",
        "model" => "A7.0",
        "appname" => "小丁TV"
    ];

    $app_name = "小丁TV";
    $package_name = "cn.xd.cc";
    $sign = "AD80F93B542B";

    $f4319D = calculate_f4319D($app_name, $package_name, $sign);
    $aes_key = generate_aes_key($f4319D, $post_data["rand"]);

    $encrypted_data = fetch_encrypted_data($url, $post_data);
    if (!$encrypted_data) {
        die("无法获取加密数据");
    }

    $transformed_data = transform_encrypted_string($encrypted_data);

    $decrypted_data = aes_decrypt($transformed_data, $aes_key);
    if (!$decrypted_data) {
        echo "处理后数据: $transformed_data\n";
        die("AES 解密失败");
    }

    $base64_decoded = base64_decode($decrypted_data);
    if (!$base64_decoded) {
        die("Base64 解码失败");
    }


    $final_data = zlib_decompress($base64_decoded);
    if (!$final_data) {
        die("zlib 解压失败");
    }

    $contents = formatJsonToCsv($final_data);
    $proxy = "https://gitee.com/yu-xinhao008/great-horizon/edit/master/zb.php?id=";  //此处改为你的php文件路径
    $txt3Final = "";
    $contentsArr = explode("\n", $contents);
    foreach ($contentsArr as $channel) {
        $name = explode(",", $channel)[0] ?? "";
        $url = explode(",", $channel)[1] ?? "";
        if (strpos($channel, "php?") !== false) {
            $txt3Final .= $name . "," . $proxy . str_replace(["&", "=", "?"], [urlencode("&"), urlencode("="), urlencode("?")], $url) . "\n";
            //$txt3Final .= $name . "," . $proxy . $url . "\n";
        } else {
            $txt3Final .= $name . "," . $url . "\n";
        }
    }
    header("content-type:text/plain");
    echo "Uesr-Agent:mitv\n\n" . $txt3Final;


} elseif (isset($_GET['id'])) {
    $url = $_GET['id'];
    $newUrl = getFinalRedirectUrl($url);
    //echo $newUrl;
    header("Location: $newUrl");
    exit();
}


?>
